package com.maidou.qiantai.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.github.pagehelper.PageInfo;
import com.maidou.qiantai.common.utils.StringAttrValueUtils;
import com.maidou.qiantai.domain.*;
import com.maidou.qiantai.dto.*;
import com.maidou.qiantai.vo.AttrGroupVo;
import com.maidou.qiantai.vo.AttrVo;
import com.maidou.qiantai.vo.SpuInfoVo;
import com.maidou.qiantai.vo.SpuVo;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.maidou.qiantai.mapper.SpuMapper;
import com.maidou.qiantai.service.ISpuService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 商品Service业务层处理
 * 
 * @author maidou
 * @date 2024-03-20
 */
@Service
public class SpuServiceImpl implements ISpuService 
{
    @Resource
    private SpuMapper spuMapper;
    @Resource
    private SpuCategoryServiceImpl spuCategoryService;
    @Resource
    private SpuImageServiceImpl spuImageService;
    @Resource
    private ProductAttrValueServiceImpl productAttrValueService;
    @Resource
    private AttrAttrgroupRelationServiceImpl attrAttrgroupRelationService;
    @Resource
    private AttrGroupServiceImpl attrGroupService ;
    @Resource
    private AttrServiceImpl attrService ;
    @Resource
    private SkuServiceImpl skuService ;

    /**
     * 查询商品
     * 
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public SpuInfoVo selectSpuById(Long id)
    {
        //商品基本信息
        Spu spu = spuMapper.selectSpuById(id);
        SpuInfoVo spuInfoVo = new SpuInfoVo();
        BeanUtils.copyProperties(spu,spuInfoVo);
        //获取商品首图
        SpuImage spuImage = new SpuImage();
        spuImage.setSpuId(id);
        spuImage.setType(0);
        List<SpuImage> spuImagesTop = spuImageService.selectSpuImageList(spuImage);
        List<String> topUrls = spuImagesTop.stream().map(item -> {
            String imgUrl = item.getImgUrl();
            return imgUrl;
        }).collect(Collectors.toList());
        spuInfoVo.setSpuTopImages(topUrls);
        //获取商品详情图
        spuImage.setType(1);
        List<SpuImage> spuImagesInfo = spuImageService.selectSpuImageList(spuImage);
        List<String> infoUrls = spuImagesInfo.stream().map(item -> {
            String imgUrl = item.getImgUrl();
            return imgUrl;
        }).collect(Collectors.toList());
        spuInfoVo.setSpuInfoImages(infoUrls);
        //获取商品属性分组（基本属性）
        ProductAttrValue productAttrValue = new ProductAttrValue();
        productAttrValue.setSpuId(id);
        List<ProductAttrValue> productAttrValueList = productAttrValueService.selectProductAttrValueList(productAttrValue);
        List<Long> attrIds = productAttrValueList.stream().map(item -> {
            Long attrId = item.getAttrId();
            return attrId;
        }).collect(Collectors.toList());
        List<Long> longs = attrAttrgroupRelationService.selectAttrGroupIdByAttrId(attrIds);
        List<AttrGroup> attrGroups = attrGroupService.selectAttrGroupBatchById(longs);
        List<AttrGroupVo> collect1 = attrGroups.stream().map(item -> {
            AttrGroupVo attrGroupVo = new AttrGroupVo();
            BeanUtils.copyProperties(item, attrGroupVo);
            Long id1 = item.getId();
            List<Attr> list = attrAttrgroupRelationService.selectToAttrByAttrGroupId(id1, attrIds, 1);
            attrGroupVo.setAttrList(list);
            return attrGroupVo;
        }).collect(Collectors.toList());
        spuInfoVo.setAttrGroupList(collect1);
        //获取商品销售属性信息
        List<Attr> attrList = attrService.selectAttrBatchByIds(attrIds);
        List<AttrVo> collect = attrList.stream().map(item -> {
            String valueSelect = item.getValueSelect();
            List<String> list = StringAttrValueUtils.SplitAttrValue(valueSelect);
            AttrVo attrVo = new AttrVo();
            BeanUtils.copyProperties(item, attrVo);
            attrVo.setValueAttrList(list);
            return attrVo;
        }).collect(Collectors.toList());
        spuInfoVo.setAttrVoList(collect);
        return spuInfoVo;
    }

    /**
     * 查询商品列表
     * 
     * @param spu 商品
     * @return 商品
     */
    @Override
    public List<SpuVo> selectSpuList(Spu spu)
    {
        List<Spu> spus = spuMapper.selectSpuList(spu);
        List<SpuVo> collect = spus.stream().map(item -> {
            Long catalogId = item.getCatalogId();
            SpuVo spuVo = new SpuVo();
            BeanUtils.copyProperties(item, spuVo);
            SpuCategory spuCategory = spuCategoryService.selectSpuCategoryById(catalogId);
            spuVo.setSpuCategory(spuCategory);
            return spuVo;
        }).collect(Collectors.toList());
        Long total = new PageInfo(spus).getTotal();
        SpuVo spuVo = new SpuVo();
        spuVo.setTotal(total);
        collect.add(0,spuVo);
        return collect;
    }

    /**
     * 新增商品
     * 
     * @param spu 商品
     * @return 结果
     */
    @Override
    public int insertSpu(Spu spu)
    {
        spu.setCreateTime(DateUtils.getNowDate());
        return spuMapper.insertSpu(spu);
    }

    /**
     * 修改商品
     * 
     * @param spu 商品
     * @return 结果
     */
    @Override
    public int updateSpu(Spu spu)
    {
        spu.setUpdateTime(DateUtils.getNowDate());
        return spuMapper.updateSpu(spu);
    }

    /**
     * 批量删除商品
     * 
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteSpuByIds(Long[] ids)
    {
        return spuMapper.deleteSpuByIds(ids);
    }

    /**
     * 删除商品信息
     * 
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public int deleteSpuById(Long id)
    {
        return spuMapper.deleteSpuById(id);
    }

    @Override
    public Spu selectSpuBySpuId(Long spuId) {
        Spu spu = spuMapper.selectSpuById(spuId);
        return spu;
    }

    /**
     * 添加商品
     * @param spuDto
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW) // 开启新事务
    @DataSource(value = DataSourceType.SLAVE) // 切换的数据源
    @Override
    public Integer insertSpuDto(SpuDto spuDto) {
        //添加商品基本信息
        SpuInfoDto spu = spuDto.getSpu();
        Spu spuDom = new Spu();
        BeanUtils.copyProperties(spu,spuDom);
        int i = spuMapper.insertSpu(spuDom);
        Long spuId = spuDom.getId();
        //添加商品首图
        List<String> spuTopImages = spu.getSpuTopImages();
        SpuImage spuImage = new SpuImage();
        spuImage.setSpuId(spuId);
        spuImage.setImgSort("1");
        spuImage.setDefaultImg(1);
        spuImage.setIsDelete(0);
        spuImage.setCreateTime(new Date());
        spuImage.setImgName("首图");
        spuImage.setType(0);
        if (spuTopImages!=null){
            for (String url:spuTopImages
            ) {
                spuImage.setImgUrl(url);
                spuImageService.insertSpuImage(spuImage);
            }
        }
        //添加商品详情图
        spuImage.setImgName("详情图");
        spuImage.setType(1);
        List<String> spuInfoImages = spu.getSpuInfoImages();
        if (spuInfoImages!=null) {
            for (String url : spuInfoImages
            ) {
                spuImage.setImgUrl(url);
                spuImageService.insertSpuImage(spuImage);
            }
        }
        //添加商品基本属性
        List<BaseAttrDto> basicAttributes = spuDto.getBasicAttributes();
        //添加分组信息
        Attr attr = new Attr();
            for (BaseAttrDto item:basicAttributes
                 ) {
            //添加基本属性分组信息
            String name = item.getName();
            AttrGroup attrGroup = new AttrGroup();
            attrGroup.setCatelogId(0l);
            attrGroup.setAttrGroupName(name);
            attrGroup.setSort(0l);
            attrGroup.setIcon("x");
            attrGroup.setDescript(name);
            attrGroup.setCreateTime(new Date());
            attrGroup.setIsDelete(0);
            attrGroup.setUpdateTime(new Date());
            attrGroupService.insertAttrGroup(attrGroup);
            Long groupId = attrGroup.getId();
            //添加基本属性值信息
            List<BaseDto> attributes = item.getAttributes();
            attr.setCatelogId(0l);
            attr.setSearchType(0);
            attr.setValueType(0);
            attr.setIcon("xxx");
            attr.setAttrType(1);
            attr.setEnable(1);
            attr.setShowDesc(0);
            attr.setCreateTime(new Date());
            attr.setIsDelete(0);
            for (BaseDto baseDto:attributes
            ) {
                attr.setValueSelect(baseDto.getValue());
                attr.setAttrName(baseDto.getName());
                attrService.insertAttr(attr);
                Long attrId = attr.getId();
                //添加商品与属性对应信息
                ProductAttrValue productAttrValue = new ProductAttrValue();
                productAttrValue.setSpuId(spuId);
                productAttrValue.setAttrValue(baseDto.getValue());
                productAttrValue.setAttrName(baseDto.getName());
                productAttrValue.setAttrSort(0l);
                productAttrValue.setAttrId(attrId);
                productAttrValue.setQuickShow(1);
                productAttrValue.setIsDelete(0);
                productAttrValue.setCreateTime(new Date());
                productAttrValueService.insertProductAttrValue(productAttrValue);
                //添加基本属性关联表信息
                AttrAttrgroupRelation attrAttrgroupRelation = new AttrAttrgroupRelation();
                attrAttrgroupRelation.setAttrGroupId(groupId);
                attrAttrgroupRelation.setAttrId(attrId);
                attrAttrgroupRelation.setIsDelete(0);
                attrAttrgroupRelation.setCreateTime(new Date());
                attrAttrgroupRelation.setAttrSort(1l);
                attrAttrgroupRelationService.insertAttrAttrgroupRelation(attrAttrgroupRelation);
            }
        }

        //添加商品销售属性
        List<SaleAttrDto> saleAttributes = spuDto.getSaleAttributes();
        for (SaleAttrDto saleAttrDto:saleAttributes
             ) {
            attr.setValueType(1);
            attr.setAttrType(0);
            List<String> values = saleAttrDto.getValues();
            String value = StringAttrValueUtils.JoinString(values);
            attr.setValueSelect(value);
            attr.setAttrName(saleAttrDto.getName());
            attrService.insertAttr(attr);
            ProductAttrValue productAttrValue = new ProductAttrValue();
            productAttrValue.setSpuId(spuId);
            productAttrValue.setAttrValue(value);
            productAttrValue.setAttrName(saleAttrDto.getName());
            productAttrValue.setAttrSort(0l);
            productAttrValue.setAttrId(attr.getId());
            productAttrValue.setQuickShow(1);
            productAttrValue.setIsDelete(0);
            productAttrValue.setCreateTime(new Date());
            productAttrValueService.insertProductAttrValue(productAttrValue);
        }
        //添加商品sku信息
        List<SkuDto> skus = spuDto.getSku();
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        sku.setCatalogId(0l);
        sku.setBrandId(0l);
        sku.setCreateTime(new Date());
        sku.setIsDelete(0);
        sku.setSaleCount(0l);
        for (SkuDto skuDto:skus
             ) {
            sku.setSkuName(skuDto.getSkuName());
            sku.setSkuDesc(skuDto.getSkuName());
            sku.setSkuDefaultImg(skuDto.getSkuUrl());
            sku.setSkuTitle(skuDto.getSkuName());
            sku.setSkuSubtitle(skuDto.getSkuName());
            sku.setPrice(new BigDecimal(skuDto.getPrice()));
            sku.setWare(skuDto.getWare());
            skuService.insertSku(sku);
        }
        return i;
    }

    /**
     * 修改商品
     * @param spuAlterDto
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW) // 开启新事务
    @DataSource(value = DataSourceType.SLAVE) // 切换的数据源
    @Override
    public Integer updateSpuDto(SpuAlterDto spuAlterDto) {
        //修改商品
        SpuInfoDto spuInfoDto = spuAlterDto.getSpu();
        Spu spu = new Spu();
        BeanUtils.copyProperties(spuInfoDto,spu);
        int i = spuMapper.updateSpu(spu);
        //删除首图信息
        Long spuId = spu.getId();
        spuImageService.deleteSpuImageBySpuIdAndType(spuId,0);
        //删除详情图信息
        spuImageService.deleteSpuImageBySpuIdAndType(spuId,1);
        //添加商品首图
        List<String> spuTopImages = spuInfoDto.getSpuTopImages();
        SpuImage spuImage = new SpuImage();
        spuImage.setSpuId(spuId);
        spuImage.setImgSort("1");
        spuImage.setDefaultImg(1);
        spuImage.setIsDelete(0);
        spuImage.setCreateTime(new Date());
        spuImage.setImgName("首图");
        spuImage.setType(0);
        if (spuTopImages!=null){


        for (String url:spuTopImages
        ) {
            spuImage.setImgUrl(url);
            spuImageService.insertSpuImage(spuImage);
        }
        }
        //添加商品详情图
        spuImage.setImgName("详情图");
        spuImage.setType(1);
        List<String> spuInfoImages = spuInfoDto.getSpuInfoImages();
        if (spuInfoImages!=null) {
            for (String url : spuInfoImages
            ) {
                spuImage.setImgUrl(url);
                spuImageService.insertSpuImage(spuImage);
            }
        }
        //属性
        List<AttrVo> attrVoList = spuAlterDto.getAttrVoList();
        List<Long> collect = attrVoList.stream().map(item -> {
            Long id = item.getId();
            return id;
        }).collect(Collectors.toList());
        attrService.deleteAttrByIds(collect.toArray(new Long[collect.size()]));
        List<AttrGroupVo> attrGroupList = spuAlterDto.getAttrGroupList();
        List<Long> groupId = attrGroupList.stream().map(item -> {
            Long id = item.getId();
            return id;
        }).collect(Collectors.toList());
        attrGroupService.deleteAttrGroupByIds(groupId.toArray(new Long[groupId.size()]));
        for (AttrGroupVo att:attrGroupList
             ) {
            List<Attr> attrList = att.getAttrList();
            List<Long> collecta = attrList.stream().map(ittm -> {
                Long id = ittm.getId();
                return id;
            }).collect(Collectors.toList());
            attrAttrgroupRelationService.deleteAttrAttrgroupRelationByAttrIdAndAttrGroupIdBatch(groupId,collecta);
            attrService.deleteAttrByIds(collecta.toArray(new Long[collecta.size()]));
        }
        attrAttrgroupRelationService.deleteAttrAttrgroupRelationByAttrIdAndAttrGroupIdBatch(groupId,collect);
        //删除sku
        skuService.deleteSkuBySpuId(spuId);
        //删除商品属性对应表
        productAttrValueService.deleteProductAttrValueBySpuId(spuId);


        //添加商品基本属性
        List<AttrGroupVo> basicAttributes =
                spuAlterDto.getAttrGroupList();
        //添加分组信息
        Attr attr = new Attr();
        for (AttrGroupVo item:basicAttributes
        ) {
            //添加基本属性分组信息
            String name = item.getAttrGroupName();
            AttrGroup attrGroup = new AttrGroup();
            attrGroup.setCatelogId(0l);
            attrGroup.setAttrGroupName(name);
            attrGroup.setSort(0l);
            attrGroup.setIcon("x");
            attrGroup.setDescript(name);
            attrGroup.setCreateTime(new Date());
            attrGroup.setIsDelete(0);
            attrGroup.setUpdateTime(new Date());
            attrGroupService.insertAttrGroup(attrGroup);
            Long attrGroupId = attrGroup.getId();
            //添加基本属性值信息
            List<Attr> attributes =
                    item.getAttrList();
            attr.setCatelogId(0l);
            attr.setSearchType(0);
            attr.setValueType(0);
            attr.setIcon("xxx");
            attr.setAttrType(1);
            attr.setEnable(1);
            attr.setShowDesc(0);
            attr.setCreateTime(new Date());
            attr.setIsDelete(0);
            for (Attr attr1:attributes
            ) {
                attr.setValueSelect(attr1.getValueSelect());
                attr.setAttrName(attr1.getAttrName());
                attrService.insertAttr(attr);
                Long attrId = attr.getId();
                //添加商品与属性对应信息
                ProductAttrValue productAttrValue = new ProductAttrValue();
                productAttrValue.setSpuId(spuId);
                productAttrValue.setAttrValue(attr1.getValueSelect());
                productAttrValue.setAttrName(attr1.getAttrName());
                productAttrValue.setAttrSort(0l);
                productAttrValue.setAttrId(attrId);
                productAttrValue.setQuickShow(1);
                productAttrValue.setIsDelete(0);
                productAttrValue.setCreateTime(new Date());
                productAttrValueService.insertProductAttrValue(productAttrValue);
                //添加基本属性关联表信息
                AttrAttrgroupRelation attrAttrgroupRelation = new AttrAttrgroupRelation();
                attrAttrgroupRelation.setAttrGroupId(attrGroupId);
                attrAttrgroupRelation.setAttrId(attrId);
                attrAttrgroupRelation.setIsDelete(0);
                attrAttrgroupRelation.setCreateTime(new Date());
                attrAttrgroupRelation.setAttrSort(1l);
                attrAttrgroupRelationService.insertAttrAttrgroupRelation(attrAttrgroupRelation);
            }
        }

        //添加商品销售属性
        List<AttrVo> saleAttributes = spuAlterDto.getAttrVoList();
        for (AttrVo saleAttrDto:saleAttributes
        ) {
            attr.setValueType(1);
            attr.setAttrType(0);
            List<String> values = saleAttrDto.getValueAttrList();
            String value = StringAttrValueUtils.JoinString(values);
            attr.setValueSelect(value);
            attr.setAttrName(saleAttrDto.getAttrName());
            attrService.insertAttr(attr);
            ProductAttrValue productAttrValue = new ProductAttrValue();
            productAttrValue.setSpuId(spuId);
            productAttrValue.setAttrValue(value);
            productAttrValue.setAttrName(saleAttrDto.getAttrName());
            productAttrValue.setAttrSort(0l);
            productAttrValue.setAttrId(attr.getId());
            productAttrValue.setQuickShow(1);
            productAttrValue.setIsDelete(0);
            productAttrValue.setCreateTime(new Date());
            productAttrValueService.insertProductAttrValue(productAttrValue);
        }
        //添加商品sku信息
        List<SkuDto> skus = spuAlterDto.getSku();
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        sku.setCatalogId(0l);
        sku.setBrandId(0l);
        sku.setCreateTime(new Date());
        sku.setIsDelete(0);
        sku.setSaleCount(0l);
        for (SkuDto skuDto:skus
        ) {
            sku.setSkuName(skuDto.getSkuName());
            sku.setSkuDesc(skuDto.getSkuName());
            sku.setSkuDefaultImg(skuDto.getSkuUrl());
            sku.setSkuTitle(skuDto.getSkuName());
            sku.setSkuSubtitle(skuDto.getSkuName());
            sku.setPrice(new BigDecimal(skuDto.getPrice()));
            sku.setWare(skuDto.getWare());
            skuService.insertSku(sku);
        }

        return i;
    }

    @Override
    public int updateSpuStatus(Long id, Integer status) {
        Spu spu = new Spu();
        spu.setId(id);
        spu.setPublishStatus(status);
        return spuMapper.updateSpu(spu);
    }
}
